package C011;

import java.util.List;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode resNode = null;
        ListNode cur = null;
        int midAdd = 0;
        int carry = 0;
        int addRes = 0;
        while (l1 != null && l2 != null) {
            midAdd = l1.val + l2.val + carry;
            addRes = midAdd % 10;
            carry = midAdd / 10;
            l1 = l1.next;
            l2 = l2.next;
            if(null == resNode){
                resNode = new ListNode(addRes);
                cur = resNode;
            }else {
                cur.next = new ListNode(addRes);
                cur = cur.next;
            }
        }
        while (l1 != null) {
            addRes = l1.val + carry;
            carry = addRes / 10;
            addRes = addRes % 10;
            cur.next = new ListNode(addRes);
            cur = cur.next;
            l1 = l1.next;
        }

        while (l2 != null) {
            addRes = l2.val + carry;
            carry = addRes / 10;
            addRes = addRes % 10;
            cur.next = new ListNode(addRes);
            cur = cur.next;
            l2 = l2.next;
        }

        if(carry != 0) {
            cur.next = new ListNode(carry);
        }

        return resNode;
    }
}